Hi Guys
I am making an external API call in my system. If the user is not logged in code will generate a 404 error
And my Code is like this
public string ExecuteGetRequest()
{
try
{
_url = Qparams != null ? Utility.WEBAPI_ENDPOINT + Type + "?" + Qparams : Utility.WEBAPI_ENDPOINT + Type; ;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_url);
if (!string.IsNullOrEmpty(SessionValues.UserID)&& !string.IsNullOrEmpty(SessionValues.AccessToken))
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(SessionValues.UserID, SessionValues.AccessToken);
string authInfo = SessionValues.UserID + ":" + SessionValues.AccessToken;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
string username = SessionValues.UserID;
String password = SessionValues.AccessToken;
String encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
}
httpWebRequest.Method = "GET";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
_result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
Log.Add(LogTypes.Error,100, ex.ToString());
}
return _result;
}
Thanks
Anonymous User
06-Dec-2014If you look at the screenshot you posted you can see that the actual exception class is a System.Net.WebException. WebException has a lot of useful properties, including the WebResponse. You can cast that response to a HttpWebResponse and then query its status code. What you can do is add a specialized exception handler for WebExceptions.
Anonymous User
06-Dec-2014First of all you should usually only catch specific types of exception instead of a catch all like you have done here so I would have your catch block as:
Obviously instead of writing to console you can do whatever you want with StatusCode and Description.
Anonymous User
06-Dec-2014You need to know at code-time what exceptions to expect, in order to catch them accordingly. As Dimitrov stated, a SQLException is thrown when the connection to an SQL server fails, so catching that specifically is a good tactic.Cast the exception to its actual type in order to get access to the WebResponse object. Then, cast that response object to HttpWebResponse in order to get the error code (and optionally, response content).